package com.css.dzj.dzjportal.common.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.css.dzj.dzjportal.common.util.R;
import com.css.dzj.dzjportal.sys.user.entity.LoginUser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 拦截逻辑
 *
 * @author liangXG
 */
@PropertySource(value = "classpath:base.properties")
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${PERMISSION_EXCLUDE_PATH}")
    private String PERMISSION_EXCLUDE_PATH;

    ObjectMapper json = new ObjectMapper();
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession loginSession = request.getSession();

        // 若ssion为空，或者session中用户为空，重定向到登录页面
        if (loginSession == null || (loginSession.getAttribute("_USER_LOGIN_INFO_") == null)) {
            response.sendRedirect(request.getContextPath() + "/html/login.html");
            return false;
        }

        LoginUser user = (LoginUser) loginSession.getAttribute("_USER_LOGIN_INFO_");
        //JSON.parseObject(loginSession.getAttribute("_USER_LOGIN_INFO_").toString(), LoginUser.class);
        String userId = user.getUserId();

        //创建一个redis连接
        ValueOperations<String, Object> vo = redisTemplate.opsForValue();
        //从redis中获取用户信息
        String userInfo = JSON.toJSONString(vo.get("_USER_LOGIN_INFO_" + userId));
        // 判断用户是否存在
        if (StringUtils.isEmpty(userInfo) || userInfo.equals("null")){
            response.sendRedirect(request.getContextPath() + "/html/login.html");
            return false;
        }
        System.out.println(userInfo);
        //redisTemplate.delete("_USER_LOGIN_INFO_");
        //权限白名单，不配置权限也不会被拦截的请求放到这里
        String[] permission_exclude_path = PERMISSION_EXCLUDE_PATH.split(",");
        //当前request请求
        String reqFunc = request.getRequestURI().replaceFirst(request.getContextPath(), "");
        if (Arrays.asList(permission_exclude_path).contains(reqFunc)) {
            return true;
        }

      /*  List permission = null;
        LoginUser userInfo = (LoginUser) loginSession.getAttribute("_USER_LOGIN_INFO_");
        if(userInfo != null){
            permission = userInfo.getPermission();
        }*/

        /*if(permission != null && permission.contains(reqFunc)){
            return true;
        }else{
            return returnErrorInfo(response, "权限不足，无法查看");
        }*/
        return true;
    }

    private boolean returnErrorInfo(HttpServletResponse response, String msg) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        //权限判断
        json.writeValue(response.getOutputStream(), R.error(500, msg));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
